package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.TurnoverDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param turnoverDTO
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(TurnoverDTO turnoverDTO) {

        //获取时间范围dateList和对应的营业额
        LocalDate beginDate = turnoverDTO.getBegin();
        LocalDate endDate = turnoverDTO.getEnd();
        ArrayList<LocalDate> dataList = new ArrayList<>();
        ArrayList<BigDecimal> turnoverList = new ArrayList<>();
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        while (!beginDate.equals(endDate.plusDays(1))) {
            dataList.add(beginDate);

            //查询计算当天总的营业额
            LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(beginDate, LocalTime.MAX);
            Integer status = Orders.COMPLETED;
            BigDecimal amount = ordersMapper.selectTurnover(beginTime, endTime, status);
            amount = amount == null ? new BigDecimal(0) : amount;
            turnoverList.add(amount);
            beginDate = beginDate.plusDays(1);
        }

        //封装vo对象响应给前端
        turnoverReportVO.setDateList(StringUtils.join(dataList, ","));
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));
        return turnoverReportVO;
    }

    /**
     * 用户统计
     *
     * @param turnoverDTO
     * @return
     */
    @Override
    public UserReportVO userStatistics(TurnoverDTO turnoverDTO) {
        LocalDate beginDate = turnoverDTO.getBegin();
        LocalDate endDate = turnoverDTO.getEnd();
        ArrayList<LocalDate> dateList = new ArrayList<>();
        ArrayList<Integer> adduserCount = new ArrayList<>();
        ArrayList<Integer> userCount = new ArrayList<>();
        while (!beginDate.equals(endDate.plusDays(1))) {
            //获取时间范围dateList
            dateList.add(beginDate);
            //查询计算当天总的新增用户数量
            LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(beginDate, LocalTime.MAX);
            Integer addCount = userMapper.selectCount(beginTime, endTime);
            addCount = addCount == null ? 0 : addCount;
            adduserCount.add(addCount);
            Integer count = userMapper.selectCount(null, endTime);
            userCount.add(count);
            beginDate = beginDate.plusDays(1);
        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(adduserCount, ","))
                .totalUserList(StringUtils.join(userCount, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param turnoverDTO
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(TurnoverDTO turnoverDTO) {
        LocalDate beginDate = turnoverDTO.getBegin();
        LocalDate endDate = turnoverDTO.getEnd();
        ArrayList<LocalDate> dateList = new ArrayList<>();
        ArrayList<Integer> ordersCount = new ArrayList<>();
        ArrayList<Integer> effectiveCount = new ArrayList<>();
        while (!beginDate.equals(endDate.plusDays(1))) {
            //获取时间范围dateList
            dateList.add(beginDate);

            //查询计算当天订单数，有效订单数
            LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(beginDate, LocalTime.MAX);
            Integer status = Orders.COMPLETED;
            Integer allCount = ordersMapper.selectCount(beginTime, endTime, null);
            Integer e_count = ordersMapper.selectCount(beginTime, endTime, status);
            allCount = allCount == null ? 0 : allCount;
            e_count = e_count == null ? 0 : e_count;
            ordersCount.add(allCount);
            effectiveCount.add(e_count);
            beginDate = beginDate.plusDays(1);
        }

        //统计总订单数和有效订单数
        int totalOrderCount = 0, validOrderCount = 0;
        for (Integer i : ordersCount) {
            totalOrderCount = totalOrderCount + i;
        }
        for (Integer i : effectiveCount) {
            validOrderCount = validOrderCount + i;
        }

        //计算订单完成率
        double orderCompletionRate = 0.0;
        if (validOrderCount != 0) {
            orderCompletionRate = validOrderCount / (double) totalOrderCount;
        }
        //响应数据给前端
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(ordersCount, ","))
                .validOrderCountList(StringUtils.join(effectiveCount, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量前十菜品
     *
     * @param turnoverDTO
     * @return
     */
    @Override
    public SalesTop10ReportVO queryTop10(TurnoverDTO turnoverDTO) {

        //查询各个菜品的销量
        LocalDate beginDate = turnoverDTO.getBegin();
        LocalDate endDate = turnoverDTO.getEnd();
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        Integer status = Orders.COMPLETED;
        List<GoodsSalesDTO> list = ordersMapper.queryTop10(beginTime, endTime, status);
        //取出菜名列表和销量列表
        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出Excel报表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {

        //获取统计的开始时间和结束时间
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDate beginDate = LocalDate.now().minusDays(30);

        //获取数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN),LocalDateTime.of(endDate,LocalTime.MAX));

        //通过poi将数据写入Excel表
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //获取Excel模板
            XSSFWorkbook sheets = new XSSFWorkbook(in);

            //获取Excel模板sheet1页
            XSSFSheet sheet1 = sheets.getSheet("sheet1");

            //写入时间至第二行
            sheet1.getRow(1).getCell(1).setCellValue("时间:"+beginDate+"至"+endDate);

            //获取第四行
            XSSFRow row4 = sheet1.getRow(3);

            //写入数据至第四行
            row4.getCell(2).setCellValue(businessData.getTurnover());
            row4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessData.getNewUsers());

            //获取第五行
            XSSFRow row5 = sheet1.getRow(4);

            //写入数据至第五行
            row5.getCell(2).setCellValue(businessData.getValidOrderCount());
            row5.getCell(4).setCellValue(businessData.getUnitPrice());

            //写入数据明细
            int row = 7;
            for (int i = 0; i <30; i++) {
                //查询当天数据明细
                BusinessDataVO businessDataByDay = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(beginDate, LocalTime.MAX));

                //获取当前行
                XSSFRow newRow = sheet1.getRow(row);

                //写入数据
                newRow.getCell(1).setCellValue(String.valueOf(beginDate));
                newRow.getCell(2).setCellValue(businessDataByDay.getTurnover());
                newRow.getCell(3).setCellValue(businessDataByDay.getValidOrderCount());
                newRow.getCell(4).setCellValue(businessDataByDay.getOrderCompletionRate());
                newRow.getCell(5).setCellValue(businessDataByDay.getUnitPrice());
                newRow.getCell(6).setCellValue(businessDataByDay.getNewUsers());

                //天数、行数加1
                beginDate = beginDate.plusDays(1);
                row++;
            }
            //写出Excel表
            ServletOutputStream outputStream = response.getOutputStream();
            sheets.write(outputStream);

            //关闭资源
            outputStream.close();
            sheets.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
